<template>
  <view class="clock-box">
    <text v-if="clockBoxData.time" class="textClass"
      >{{ clockBoxData.time.format('HH:mm:ss') }}
    </text>
    <button
      :disabled="clockBoxData.disabled || clockBoxData.address === '未知'"
      :loading="clockBoxData.isLoading || clockBoxData.address === '未知'"
      class="btn"
      type="primary"
      @click="clockFn"
    >
      <text v-if="flagGeocode"> 获取位置中</text>
      <text v-else>
        {{ clockBoxData.clockTxt }}
      </text>
    </button>
    <view class="msgInfo">
      <icon
        v-if="clockBoxData.address === '未知'"
        :size="rpxTopx(32)"
        color="#FF3E0B"
        type="warn"
      />
      <icon v-else :size="rpxTopx(32)" color="#00B42A" type="success" />
      <text @tap="showMap">打卡位置：{{ clockBoxData.address }}</text>
    </view>
  </view>
  <uni-popup ref="popup" background-color="#fff">
    <view class="lateClock">
      <view class="lateClock-header">
        <i class="iconfont icon-cuowuguanbiquxiao" @click="closePopup"></i>
        <h3>是否迟到打卡?</h3>
        <p></p>
      </view>
      <view class="lateClock-list">
        <view class="list">
          <p>打卡时间 {{ dayjs().format('HH:mm') }}</p>
          <text>
            <i class="iconfont icon-weibiaoti-3" />
            {{ clockBoxData.address }}
          </text>
        </view>
        <view class="list">
          <p>备注</p>
          <input placeholder="请输入迟到原因" />
        </view>
        <button @tap="handleLateAttendance">迟到打卡</button>
      </view>
    </view>
  </uni-popup>
  <uni-popup ref="popupZaotui" background-color="#fff">
    <view class="lateClock">
      <view class="lateClock-header">
        <i class="iconfont icon-cuowuguanbiquxiao" @click="closePopupZaotui"></i>
        <h3>是否早退打卡?</h3>
        <p></p>
      </view>
      <view class="lateClock-list">
        <view class="list">
          <p>打卡时间 {{ dayjs().format('HH:mm') }}</p>
          <text>
            <i class="iconfont icon-weibiaoti-3" />
            {{ clockBoxData.address }}
          </text>
        </view>
        <view class="list">
          <p>备注</p>
          <input placeholder="请输入早退原因" />
        </view>
        <button @tap="handleLateAttendance">早退打卡</button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import dayjs from 'dayjs'
import { defineEmits, defineProps, ref } from 'vue'
import { rpxTopx } from '@/hook/convertUnit'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { addAttendance } from '@/api/attendance'
import { getUserProfile } from '@/api/system/user'
import { useDeviceId } from '@/utils/getInitDeviceId.js'

const props = defineProps(['punchType', 'userId', 'deptId'])
const emit = defineEmits(['openSuccessView'])
const popup = ref(null)
const popupZaotui = ref(null)
const { deviceId, isReady: deviceIdReady, isError: deviceIdError } = useDeviceId()
// 组件属性
const clockBoxData = ref({
  time: dayjs(), // 当前时间
  address: '未知', // 当前地址
  isLoading: false, // 打卡加载效果
  disabled: true, // 未到打卡按钮
  clockTxt: '定位中', //
  clockStatus: '正常', // 打卡状态
})
let location = ref({
  lat: 0, //维度
  lng: 0, //经度
})
let flagGeocode = ref(false)

// 关闭弹出层
const closePopup = () => {
  popup.value.close()
}
const closePopupZaotui = () => {
  popupZaotui.value.close()
}
// 打卡
const clockFn = async () => {
  clockBoxData.disabled = true
  let params = {
    punchType: props.punchType, // 打卡类型
    type: clockBoxData.clockStatus, // 打卡状态
    locationLatitude: location.value.lat,
    locationLongitude: location.value.lng,
    userId: props.userId,
    deptId: props.deptId,
    deviceCode: deviceId.value,
  }
  if (clockBoxData.clockStatus === '迟到') {
    popup.value.open('bottom')
    setTimeout(() => {
      clockBoxData.value.isLoading = false
    }, 1000)
  } else if (clockBoxData.clockStatus === '早退') {
    popupZaotui.value.open('bottom')
    setTimeout(() => {
      clockBoxData.value.isLoading = false
    }, 1000)
  } else {
    let { code } = await addAttendance(params)
    if (code === 200) {
      emit('openSuccessView')
    }
  }
}

let intervalRef = ref(null) // 当前时间计时器
const locationList = ref([
  { lat: 32.996571, lng: 112.567469 }, // 鑫源
  { lat: 32.128963, lng: 114.131159 }, // 信仰
  { lat: 33.040452, lng: 112.531317 }, // 南阳市卧龙区冯楼黄羽种鸡场
  { lat: 32.991163, lng: 114.012867 }, // 开发区金河办事处东高社区卫生服务站
  { lat: 32.651956, lng: 112.129627 }, // 邓州市产业孵化园
  { lat: 34.725066, lng: 113.738231 }, // 郑州大宇颐园
  { lat: 34.748717, lng: 113.675351 }, // 郁金香苑
  { lat: 32.998095, lng: 112.599547 }, // 花境公园
  { lat: 34.760549, lng: 113.770115 }, // 郑州绿地之窗景峰座1号楼
])
//上下班打卡时间
const time1 = ref(null)
const time2 = ref(null)
const time3 = ref(null)
const time4 = ref(null)

const getWeek = () => {
  let datas = dayjs().day()
  let week = ['日', '一', '二', '三', '四', '五', '六']
  return '星期' + week[datas]
}
// 新疆打卡
let userIdAttendabceArr = [82] // 罗平
// 郑州打卡
let deptAttendabce = [8253, 6707, 6708, 8254, 6701, 6702, 6703, 6704, 8255, 8256, 8242] // 8242郑州部门id
let deptAttendabceZhenZhou = ref(null) // 8242郑州部门id
// 郑州郑州绿地之窗景峰座1号楼打卡  钟正，史闯，尚州合，周旭, 李婷,张尧
let cxyuserIdAttendabceArr = [147,106,108,99,163,97] // 郑州郑州绿地之窗景峰座1号楼打卡id
let userIdAttendabce = ref(null) // 用户
const timeFn = () => {
  // 新疆打卡
  if (userIdAttendabceArr.includes(userIdAttendabce.value)) {
    time1.value = dayjs().hour(8).minute(0).second(59)
    time2.value = dayjs().hour(12).minute(30).second(0)
    time3.value = dayjs().hour(14).minute(30).second(59)
    time4.value = dayjs().hour(19).minute(0).second(0)
  } else if (deptAttendabce.includes(deptAttendabceZhenZhou.value)) {
    // 郑州打卡
    if (getWeek() === '星期一') {
      time1.value = dayjs().hour(7).minute(50).second(59)
    } else {
      time1.value = dayjs().hour(8).minute(30).second(59)
    }
    time2.value = dayjs().hour(12).minute(0).second(0)
    time3.value = dayjs().hour(14).minute(0).second(59)
    time4.value = dayjs().hour(18).minute(30).second(0)
  } else if (cxyuserIdAttendabceArr.includes(deptAttendabceZhenZhou.value)) {
    // 郑州打卡
    if (getWeek() === '星期一') {
      time1.value = dayjs().hour(7).minute(50).second(59)
    } else {
      time1.value = dayjs().hour(9).minute(0).second(59)
    }
    time2.value = dayjs().hour(12).minute(0).second(0)
    time3.value = dayjs().hour(14).minute(0).second(59)
    time4.value = dayjs().hour(19).minute(0).second(0)
  }else {
    //上下班打卡时间
    if (getWeek() === '星期一') {
      time1.value = dayjs().hour(7).minute(50).second(59)
    } else {
      time1.value = dayjs().hour(8).minute(0).second(59)
    }
    time2.value = dayjs().hour(12).minute(0).second(0)
    time3.value = dayjs().hour(14).minute(30).second(59)
    time4.value = dayjs().hour(18).minute(30).second(0)
  }
}

//进行经纬度转换为距离的计算
function Rad(d) {
  return (d * Math.PI) / 180.0 //经纬度转换成三角函数中度分表形式。
}

// 修改后的距离计算函数
const GetDistance = (lat1, lng1, lat2, lng2) => {
  const radLat1 = Rad(lat1)
  const radLat2 = Rad(lat2)
  const a = radLat1 - radLat2
  const b = Rad(lng1) - Rad(lng2)
  const s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2),
      ),
    )
  return s * 6378.137 // 返回公里数
}

// 检测定位权限
function checkLocationPermission() {
  uni.getSetting({
    success(res) {
      if (!res.authSetting['scope.userLocation']) {
        // 未授权，触发友好提示
        showPermissionDialog()
      } else {
        // 已授权，继续正常流程
        startLocationService()
      }
    },
    fail(err) {
      console.error('获取权限设置失败', err)
    },
  })
}

// 提示用户授权
function showPermissionDialog() {
  uni.showModal({
    title: '需要定位权限',
    content: '为了更好地为您提供服务，我们需要获取您的位置信息。请授权定位权限以继续使用。',
    confirmText: '立即授权',
    cancelText: '暂不授权',
    success(res) {
      if (res.confirm) {
        // 用户点击“立即授权”，跳转到权限设置页面
        openAppSettings()
      } else {
        // 用户点击“暂不授权”，提示功能受限
        uni.showToast({
          title: '部分功能将无法使用',
          icon: 'none',
        })
      }
    },
  })
}

const checkValidLocation = (currentLat, currentLng) => {
  return locationList.value.some((item) => {
    const distance = GetDistance(currentLat, currentLng, item.lat, item.lng)
    return distance <= 0.8
  })
}
const systemInfo = uni.getSystemInfoSync()
const isAndroid = systemInfo.platform.toLowerCase() === 'android'
// const isIOS = systemInfo.platform.toLowerCase() === 'ios'
const profile = ref(null)
onLoad(async () => {
  profile.value = (await getUserProfile()).data
  deptAttendabceZhenZhou.value = profile.value.deptId
  userIdAttendabce.value = profile.value.userId // 用户
  timeFn()
  clockBoxData.value.isLoading = true

  // 安卓 用 geo 苹果用wgs
  uni.getLocation({
    type: isAndroid ? 'gcj02' : 'wgs84',
    geocode: true,
    isHighAccuracy: false, // 高精度定位，会调用gps获取高精度坐标
    success: function (res) {
      // console.log(res, '获取地址成功')
      clockBoxData.value.isLoading = false
      location.value.lat = res.latitude
      location.value.lng = res.longitude
      flagGeocode.value = false
      console.log(location.value)
      if (res.address) {
        clockBoxData.value.address = isAndroid ? res.address?.poiName : res.address?.street
        clockBoxData.value.isLoading = false
        // clockBoxData.value.clockTxt = '外勤打卡'
        // 修改后的位置判断逻辑
        const isValidLocation = checkValidLocation(location.value.lat, location.value.lng)
        intervalRef.value = setInterval(() => {
          // 获取当前的时间
          clockBoxData.value.time = dayjs()
          // clockBoxData.value.time = dayjs().hour(23).minute(40)
          if (isValidLocation) {
            // 上班早上打卡  当前时间 大于 8
            if (
              clockBoxData.value.time.valueOf() >= time1.value.valueOf() &&
              props.punchType === '上午上班'
            ) {
              clockBoxData.value.isLoading = false
              clockBoxData.value.clockTxt = '上班打卡'
              clockBoxData.value.disabled = false
              clockBoxData.clockStatus = '迟到'
              // 上班打卡接口
            } else if (props.punchType === '上午下班') {
              // 添加早退判断（当前时间小于下班时间time2）
              const isEarly = clockBoxData.value.time.valueOf() < time2.value.valueOf()

              clockBoxData.value.isLoading = false
              clockBoxData.value.clockTxt = '下班打卡'
              clockBoxData.value.disabled = false
              clockBoxData.clockStatus = isEarly ? '早退' : '正常' // 根据时间判断状态
            } else if (
              clockBoxData.value.time.valueOf() >= time3.value.valueOf() &&
              props.punchType === '下午上班'
            ) {
              // 上班晚上打卡
              clockBoxData.value.isLoading = false
              clockBoxData.value.clockTxt = '上班打卡'
              clockBoxData.value.disabled = false
              clockBoxData.clockStatus = '迟到'
            } else if (props.punchType === '下午下班') {
              // 添加早退判断（当前时间小于下班时间time4）
              const isEarly = clockBoxData.value.time.valueOf() < time4.value.valueOf()

              clockBoxData.value.isLoading = false
              clockBoxData.value.clockTxt = '下班打卡'
              clockBoxData.value.disabled = false
              clockBoxData.clockStatus = isEarly ? '早退' : '正常' // 根据时间判断状态
            } else {
              clockBoxData.value.isLoading = false
              clockBoxData.value.clockTxt = '打卡'
              clockBoxData.value.disabled = false
              clockBoxData.clockStatus = '正常'
            }
          } else {
            if (props.punchType === '上午上班') {
              clockBoxData.value.clockTxt = '外勤上班打卡'
              clockBoxData.value.isLoading = false
              clockBoxData.value.disabled = false
              // 上班打卡接口
            }
            if (props.punchType === '上午下班') {
              clockBoxData.value.isLoading = false
              clockBoxData.value.clockTxt = '外勤下班打卡'
              clockBoxData.value.disabled = false
              // 上班打卡接口
            }
            if (props.punchType === '下午上班') {
              clockBoxData.value.isLoading = false
              clockBoxData.value.clockTxt = '外勤上班打卡'
              clockBoxData.value.disabled = false
              // 上班打卡接口
            }
            if (props.punchType === '下午下班') {
              clockBoxData.value.isLoading = false
              clockBoxData.value.clockTxt = '外勤下班打卡'
              clockBoxData.value.disabled = false
              // 上班打卡接口
            }
            clockBoxData.clockStatus = '外勤'
          }
        }, 1000)
      }
    },
    fail: function (e) {
      console.log(e, '获取地址失败')
      flagGeocode.value = true
      uni.showToast({
        title: '获取地址失败，将导致部分功能不可用',
        icon: 'none',
      })
      // checkLocationPermission();
    },
  })
})

const handleLateAttendance = async () => {
  let params = {
    punchType: props.punchType, // 打卡类型
    type: clockBoxData.clockStatus, // 打卡状态
    locationLatitude: location.value.lat,
    locationLongitude: location.value.lng,
    userId: props.userId,
    deptId: props.deptId,
    deviceCode: deviceId.value,
  }
  let { code } = await addAttendance(params)
  if (code === 200) {
    emit('openSuccessView')
  }
  // emit('showSuccessFn')
}

const showMap = () => {
  uni.openLocation({
    latitude: location.value.lat,
    longitude: location.value.lng,
    name: clockBoxData.value.address,
  })
}

onUnload(() => {
  clearInterval(intervalRef.value)
})
</script>

<style lang="scss" scoped>
@import '@/static/style/index.scss';

.clock-box {
  width: 616rpx;
  padding: 32rpx 0rpx;
  flex-direction: column;
  margin: 16rpx 0;
  border-radius: 16rpx;
  background-color: #fff;
  box-shadow: 0 4rpx 16rpx 0 #0000000d;
  @include flex(center, center);

  .textClass {
    align-self: stretch;
    color: #1d2129;
    text-align: center;
    font-family: 'Noto Sans';
    font-size: 72rpx;
    font-style: normal;
    font-weight: 700;
    line-height: 100.8rpx;
  }

  .btn {
    @include flex(center, center);
    border-radius: 60rpx;
    height: 92rpx;
    width: 324rpx;
    margin-top: 12rpx;
    margin-bottom: 32rpx;
    background-color: #165dff;
    font-family: 'PingFang SC';
    font-size: 32rpx;
    font-style: normal;
    font-weight: 500;
    line-height: 44.8rpx;
  }

  .msgInfo {
    color: #86909c;
    font-size: 26rpx;
    font-weight: 400;
    @include flex(center, space-between);
    padding: 0 10rpx;

    text {
      display: inline-block;
      margin-left: 12rpx;
    }
  }
}

:deep(.lateClock) {
  padding: 28rpx 32rpx;

  .lateClock-header {
    @include flex(center, space-between);

    .iconfont {
      color: #1d2129;
    }

    h3 {
      color: #1d2129;
      font-size: 34rpx;
      font-weight: 500;
    }
  }

  .lateClock-list {
    margin-top: 38rpx;

    .list {
      margin-bottom: 20rpx;

      p {
        color: #1d2129;
        font-size: 32rpx;
        font-style: normal;
        font-weight: 400;
      }

      span {
        color: #86909c;
        font-size: 28rpx;
        font-style: normal;
        font-weight: 400;
        margin-top: 4rpx;
        display: inline-block;
      }

      input {
        font-size: 28rpx;
        margin-top: 4rpx;
      }
    }

    button {
      margin-top: 80rpx;
      background-color: #f53f3e;
      color: #fff;
    }
  }
}
</style>
